<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>优惠券模板管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/common.css">
</head>
<body>
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>优惠券模板管理</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#templateModal">
            新增模板
        </button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <div class="row g-3">
            <div class="col-md-3">
                <input type="text" id="searchShopNumber" class="form-control" placeholder="输入店铺编号搜索">
            </div>
            <div class="col-md-3">
                <input type="text" id="searchTemplateName" class="form-control" placeholder="输入模板名称搜索">
            </div>
            <div class="col-md-3">
                <select id="searchStatus" class="form-select">
                    <option value="">全部状态</option>
                    <option value="0">生效中</option>
                    <option value="1">已结束</option>
                </select>
            </div>
            <div class="col-md-3">
                <button class="btn btn-success w-100" onclick="queryTemplateList(1)">搜索</button>
            </div>
        </div>
    </div>

    <!-- 模板列表 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-bordered">
                <thead class="table-primary">
                <tr>
                    <th>模板ID</th>
                    <th>店铺编号</th>
                    <th>模板名称</th>
                    <th>优惠类型</th>
                    <th>适用范围</th>
                    <th>库存</th>
                    <th>状态</th>
                    <th>有效期</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="templateTableBody">
                <tr><td colspan="9" class="text-center">加载中...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container"></div>
</div>

<!-- 新增/编辑模板弹窗 -->
<div class="modal fade" id="templateModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">新增优惠券模板</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="templateForm">
                    <input type="hidden" id="templateId">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="shopNumber" class="form-label">店铺编号 <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="shopNumber" required placeholder="平台券填99999，店铺券填对应店铺编号">
                        </div>
                        <div class="col-md-6">
                            <label for="templateName" class="form-label">模板名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="templateName" required placeholder="请输入模板名称">
                        </div>
                        <div class="col-md-3">
                            <label for="source" class="form-label">券来源 <span class="text-danger">*</span></label>
                            <select class="form-select" id="source" required>
                                <option value="0">店铺券</option>
                                <option value="1">平台券</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="target" class="form-label">适用范围 <span class="text-danger">*</span></label>
                            <select class="form-select" id="target" required>
                                <option value="0">指定商品</option>
                                <option value="1">全商品</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="type" class="form-label">优惠类型 <span class="text-danger">*</span></label>
                            <select class="form-select" id="type" required onchange="showDiscountFields()">
                                <option value="0">立减券</option>
                                <option value="1">满减券</option>
                                <option value="2">折扣券</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="stock" class="form-label">库存 <span class="text-danger">*</span></label>
                            <input type="number" min="0" class="form-control" id="stock" required placeholder="请输入优惠券库存">
                        </div>
                        <div class="col-md-6" id="goodsGroup">
                            <label for="goods" class="form-label">指定商品分类ID</label>
                            <input type="text" class="form-control" id="goods" placeholder="适用范围为指定商品时填写，多个分类ID用逗号分隔">
                        </div>
                        <div class="col-md-6" id="minAmountGroup" style="display: none;">
                            <label for="minAmount" class="form-label">最低消费金额（元）</label>
                            <input type="number" step="0.01" min="0" class="form-control" id="minAmount" placeholder="满减券/折扣券必填">
                        </div>
                        <div class="col-md-6" id="discountGroup" style="display: none;">
                            <label for="discount" class="form-label">折扣比例</label>
                            <input type="number" step="0.01" min="0.1" max="0.99" class="form-control" id="discount" placeholder="折扣券必填（如8折填0.8）">
                        </div>
                        <div class="col-md-6" id="reduceAmountGroup" style="display: none;">
                            <label for="reduceAmount" class="form-label">立减金额（元）</label>
                            <input type="number" step="0.01" min="0.01" class="form-control" id="reduceAmount" placeholder="立减券必填">
                        </div>
                        <div class="col-md-6">
                            <label for="validStartTime" class="form-label">生效时间 <span class="text-danger">*</span></label>
                            <input type="datetime-local" class="form-control" id="validStartTime" required>
                        </div>
                        <div class="col-md-6">
                            <label for="validEndTime" class="form-label">失效时间 <span class="text-danger">*</span></label>
                            <input type="datetime-local" class="form-control" id="validEndTime" required>
                        </div>
                        <div class="col-md-6">
                            <label for="receiveRule" class="form-label">领取规则 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="receiveRule" required placeholder='JSON格式，如{"limit":1,"perUser":3}'>
                        </div>
                        <div class="col-md-6">
                            <label for="consumeRule" class="form-label">消耗规则 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="consumeRule" required placeholder='JSON格式，如{"minAmount":100}'>
                        </div>
                        <div class="col-md-12">
                            <label for="templateStatus" class="form-label">模板状态 <span class="text-danger">*</span></label>
                            <select class="form-select" id="templateStatus" required>
                                <option value="0">生效中</option>
                                <option value="1">已结束</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveTemplate()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/common.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 10;

    window.onload = function () {
        // 初始化优惠类型字段显示
        showDiscountFields();
        // 监听优惠类型变化
        document.getElementById("type").addEventListener("change", showDiscountFields);
        // 监听适用范围变化
        document.getElementById("target").addEventListener("change", function () {
            document.getElementById("goodsGroup").style.display = this.value === "0" ? "block" : "none";
        });
        // 查询模板列表
        queryTemplateList(currentPage);
    };

    // 根据优惠类型显示对应字段
    function showDiscountFields() {
        const type = document.getElementById("type").value;
        // 隐藏所有特殊字段
        document.getElementById("minAmountGroup").style.display = "none";
        document.getElementById("discountGroup").style.display = "none";
        document.getElementById("reduceAmountGroup").style.display = "none";

        switch (type) {
            case "0": // 立减券
                document.getElementById("reduceAmountGroup").style.display = "block";
                break;
            case "1": // 满减券
                document.getElementById("minAmountGroup").style.display = "block";
                document.getElementById("reduceAmountGroup").style.display = "block";
                break;
            case "2": // 折扣券
                document.getElementById("minAmountGroup").style.display = "block";
                document.getElementById("discountGroup").style.display = "block";
                break;
        }
    }

    // 格式化优惠类型
    function formatCouponType(type) {
        const typeMap = { 0: "立减券", 1: "满减券", 2: "折扣券" };
        return typeMap[type] || "未知类型";
    }

    // 格式化适用范围
    function formatTarget(target, goods) {
        if (target === 1) return "全商品";
        if (!goods) return "未指定";
        return `指定分类（${goods}）`;
    }

    // 查询模板列表
    async function queryTemplateList(pageNum) {
        try {
            const shopNumber = document.getElementById("searchShopNumber").value;
            const templateName = document.getElementById("searchTemplateName").value;
            const status = document.getElementById("searchStatus").value;

            const res = await axios.get("/api/coupon-templates/page", {
                params: {
                    pageNum,
                    pageSize,
                    shopNumber: shopNumber || undefined,
                    name: templateName || undefined,
                    status: status || undefined
                }
            });

            const { records, total } = res.data;
            currentPage = pageNum;
            const tableBody = document.getElementById("templateTableBody");
            tableBody.innerHTML = "";

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="9" class="text-center">暂无数据</td></tr>';
                return;
            }

            records.forEach(template => {
                const validPeriod = `${Common.formatDate(template.validStartTime).split(" ")[0]} 至 ${Common.formatDate(template.validEndTime).split(" ")[0]}`;
                const row = `
                        <tr>
                            <td>${template.id}</td>
                            <td>${template.shopNumber}</td>
                            <td>${template.name}</td>
                            <td>${formatCouponType(template.type)}</td>
                            <td>${formatTarget(template.target, template.goods)}</td>
                            <td>${template.stock}</td>
                            <td>${Common.formatTemplateStatus(template.status)}</td>
                            <td>${validPeriod}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="editTemplate(${template.id})">编辑</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteTemplate(${template.id})">删除</button>
                            </td>
                        </tr>
                    `;
                tableBody.innerHTML += row;
            });

            Common.renderPagination(total, pageNum, pageSize, queryTemplateList);
        } catch (err) {
            Common.errorMsg("查询优惠券模板失败：" + err.message);
            document.getElementById("templateTableBody").innerHTML = '<tr><td colspan="9" class="text-center">查询失败</td></tr>';
        }
    }

    // 编辑模板
    async function editTemplate(templateId) {
        try {
            const res = await axios.get(`/api/coupon-templates/${templateId}`);
            const template = res.data;

            document.getElementById("templateId").value = template.id;
            document.getElementById("shopNumber").value = template.shopNumber;
            document.getElementById("templateName").value = template.name;
            document.getElementById("source").value = template.source;
            document.getElementById("target").value = template.target;
            document.getElementById("type").value = template.type;
            document.getElementById("stock").value = template.stock;
            document.getElementById("goods").value = template.goods || "";
            document.getElementById("validStartTime").value = moment(template.validStartTime).format("YYYY-MM-DDTHH:mm");
            document.getElementById("validEndTime").value = moment(template.validEndTime).format("YYYY-MM-DDTHH:mm");
            document.getElementById("receiveRule").value = template.receiveRule || '{"limit":1,"perUser":1}';
            document.getElementById("consumeRule").value = template.consumeRule || '{"minAmount":0}';
            document.getElementById("templateStatus").value = template.status;

            // 显示对应字段
            showDiscountFields();
            document.getElementById("goodsGroup").style.display = template.target === 0 ? "block" : "none";

            // 解析消耗规则填充字段
            const consumeRule = JSON.parse(template.consumeRule || "{}");
            document.getElementById("minAmount").value = consumeRule.minAmount || "";
            document.getElementById("discount").value = consumeRule.discount || "";
            document.getElementById("reduceAmount").value = consumeRule.reduceAmount || "";

            document.getElementById("modalTitle").textContent = "编辑优惠券模板";
            new bootstrap.Modal(document.getElementById("templateModal")).show();
        } catch (err) {
            Common.errorMsg("加载模板信息失败：" + err.message);
        }
    }

    // 保存模板
    async function saveTemplate() {
        const shopNumber = document.getElementById("shopNumber").value;
        const templateName = document.getElementById("templateName").value;
        const source = document.getElementById("source").value;
        const target = document.getElementById("target").value;
        const type = document.getElementById("type").value;
        const stock = document.getElementById("stock").value;
        const validStartTime = document.getElementById("validStartTime").value;
        const validEndTime = document.getElementById("validEndTime").value;
        const receiveRule = document.getElementById("receiveRule").value;
        const consumeRule = document.getElementById("consumeRule").value;
        const status = document.getElementById("templateStatus").value;
        const templateId = document.getElementById("templateId").value;

        // 基础校验
        if (!shopNumber || !templateName || !source || !target || !type || !stock || !validStartTime || !validEndTime || !receiveRule || !consumeRule) {
            Common.errorMsg("请填写必填字段！");
            return;
        }

        // 校验JSON格式
        try {
            JSON.parse(receiveRule);
            JSON.parse(consumeRule);
        } catch (e) {
            Common.errorMsg("领取规则或消耗规则格式不正确（需JSON格式）！");
            return;
        }

        // 构建模板数据
        const templateData = {
            shopNumber: parseInt(shopNumber),
            name: templateName,
            source: parseInt(source),
            target: parseInt(target),
            type: parseInt(type),
            stock: parseInt(stock),
            goods: document.getElementById("goods").value || "",
            validStartTime: new Date(validStartTime).getTime(),
            validEndTime: new Date(validEndTime).getTime(),
            receiveRule: receiveRule,
            consumeRule: consumeRule,
            status: parseInt(status)
        };

        try {
            if (templateId) {
                templateData.id = parseInt(templateId);
                await axios.put("/api/coupon-templates", templateData);
                Common.successMsg("编辑模板成功！");
            } else {
                await axios.post("/api/coupon-templates", templateData);
                Common.successMsg("新增模板成功！");
            }

            bootstrap.Modal.getInstance(document.getElementById("templateModal")).hide();
            queryTemplateList(currentPage);
            document.getElementById("templateForm").reset();
            document.getElementById("templateId").value = "";
            document.getElementById("modalTitle").textContent = "新增优惠券模板";
        } catch (err) {
            Common.errorMsg("保存模板失败：" + err.message);
        }
    }

    // 删除模板（逻辑删除）
    function deleteTemplate(templateId) {
        Common.confirmMsg("确定要删除该模板吗？（逻辑删除，可恢复）", async () => {
            try {
                await axios.delete(`/api/coupon-templates/${templateId}`);
                Common.successMsg("删除模板成功！");
                queryTemplateList(currentPage);
            } catch (err) {
                Common.errorMsg("删除模板失败：" + err.message);
            }
        });
    }
</script>
</body>
</html>